package com.snowj.apaas.web;

import com.snowj.apaas.domain.auto.Clients;
import com.snowj.apaas.service.ClientService;
import com.snowj.apaas.service.utils.PaginationUtil;
import com.snowj.apaas.service.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@Api(value = "客户管理", tags = {"客户管理接口"})
@RestController
@RequestMapping("/api")
public class ClientsController {

    private final ClientService clientService;

    public ClientsController(ClientService clientService) {
        this.clientService = clientService;
    }

    /**
     * 列出所有客户
     *
     * @return
     */
    @ApiOperation("列出所有客户")
    @GetMapping("/clients/all")
    public ResponseEntity<List<Clients>> listAllClients() {
        List<Clients> clients = clientService.listAllClients();
        return ResponseEntity.ok(clients);
    }


    /**
     * 列出客户列表
     *
     * @param name     客户名称
     * @param pageable
     * @return
     */
    @ApiOperation("列出客户列表")
    @GetMapping("/clients")
    public ResponseEntity<List<Clients>> listClients(String name, Pageable pageable) {
        Page<Clients> page = clientService.listClients(name, pageable);
        HttpHeaders httpHeaders = PaginationUtil.generatePaginationHttpHeaders(page);
        return ResponseEntity.status(HttpStatus.OK)
                .headers(httpHeaders)
                .body(page.getContent());
    }

    /**
     * 根据id查找客户
     *
     * @param id 客户编号
     * @return
     */
    @ApiOperation("根据id查找客户")
    @GetMapping("/clients/{id}")
    public ResponseEntity<Clients> findClientById(@PathVariable Long id) {
        Optional<Clients> clientsOptional = clientService.findClientById(id);
        return ResponseUtil.wrapOrNotFound(clientsOptional);
    }

    /**
     * 创建客户
     *
     * @param clients 客户信息
     * @return
     */
    @ApiOperation("创建客户")
    @PostMapping("/clients")
    public ResponseEntity<Clients> createClient(@RequestBody Clients clients) {
        Clients c = clientService.createClient(clients);
        return ResponseEntity.ok(c);
    }

    /**
     * 更新客户信息
     *
     * @param clients 客户信息
     * @return
     */
    @ApiOperation("更新客户信息")
    @PutMapping("/clients")
    public ResponseEntity<Clients> updateClient(@RequestBody Clients clients) {
        Clients c = clientService.updateClient(clients);
        return ResponseEntity.ok(c);
    }

    /**
     * 删除客户
     * @param id 客户编号
     */
    @ApiOperation("删除客户")
    @DeleteMapping("/clients/{id}")
    public void deleteClient(@PathVariable Long id) {
        clientService.deleteClient(id);
    }
}
